//创建html播放器
document.write('<div id="videoplace"></div>');
videoplace.innerHTML='\
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">\
<link rel="stylesheet" type="text/css" href="css/html_5.css">\
<span id="loading_info">加载媒体，可能要几秒</span>\
<div id="loading" style="display:none;">\
<div id="div1">\
<div id="div2">\
<div id="div2_1_1">\
<span id="div2_1_1_1">菜单</span>\
<div id="div2_1" class="btn-group">\
<b><input id="paus" type="button" class="btn btn-default" value="播放"/></b>\
<b><input id="fullscreen" type="button" class="btn btn-default" value="全屏f"/></b>\
<b><input id="rotate" type="button" class="btn btn-default" value="旋转r"/></b>\
<b><input id="reload" type="button" class="btn btn-default" value="重加载"/></b>\
<b><input id="speed" type="button" class="btn btn-default" value="速度v"/></b>\
<b><input id="oped" type="button" class="btn btn-default" value="区间"/></b>\
<b><input id="soure" type="button" class="btn btn-default" value="去源址"/></b>\
<b><a href='+downloadfu()+' download><input id="download" type="button" class="btn btn-default" value="下载"/></a></b>\
<div id="div2_2">\
<b> <input id="volumerange" type="range" min="0" max="100"></input><span id="volumerange_val">音量</span></b>\
<span id="showinfo"></span>\
</div>\
</div>\
</div>\<div id="div2_3">\
<span id="showProgress"></span><span id="lookProgress"></span>\
</div>\<div id="div2_4">\
<div id="progressWrap" class="progress">\
<div id="loadProgress" class="progress-bar progress-bar-success progress-bar-striped active">\
<div id="playProgress" class="progress-bar progress-bar-success"></div></div></div>\
</div>\<div id="div2_5">\
<a href="https://gitee.com/qydysky/htmlBoFangQijs/commits/master" target="update"><span id="day_time">-html.js</span></a>\
</div>\
</div>\
</div>\
<div>\
<div id="notice_div" class="alert alert-success"></div>\
<video id="videoElement"></video>\
</div>\
</div>\
';
//声明全局变量
	var value=new Array(),
		value=["videoElement","loading","loading_info","div1","div2",
		"progressWrap","playProgress","loadProgress","showProgress",
		"lookProgress","soure","volumerange","volumerange_val","paus",
		"showinfo","fullscreen","rotate","reload","speed","error_msg",
		"download","oped","notice_div"];
	for(var i=0;i<value.length;i++){
		window[value[i]]=document.getElementById(value[i]);
	}i=undefined;
	value=[
		["flvPlayer",],
		["player",1],
        ["rotatevalue",0],
        ["winWidth",""],
        ["winHeight",""],
        ["W_H",""],
        ["h",""],
        ["w",""],
        ["H",""],
        ["W",""],
        ["volume",0.1],
        ["currentTime",5],
        ["r",GetQueryString('r')],
        ["t",GetQueryString('t')],
		["u",GetQueryString('u')],
		["n",GetQueryString('n')],
		["max",GetQueryString('max')],
        ["screen_way_val",screen_way()],
		["autofixwin_val",1],
		["mouseX",0],
		["mouse_inpro",0],
		["op",0],
		["ed",0],
		["set_oped",0],
		["sign",1],
    ];
	for(var i=0;i<value.length;i++){
		window[value[i][0]]=value[i][1];
	}i=undefined;value=undefined;
	var input=document.getElementsByTagName("input");
//首要事件
	//引入js
	//console.log(typeof flvjs);
		var js={
			_doc:document.getElementsByTagName('head')[0],
			nowloading:-1,
			nowloaded:0,
			js:[//[加载?,地址]顺序加载
				[0,'js/jquery-3.3.1.min.js'],
				[0,'js/popper.min.js'],
				[0,'js/bootstrap/js/bootstrap.min.js'],
				[1,'js/sweetalert2.all.min.js'],
				[1,'js/flv.min_2.js'],
				[1,'js/hls.js']
				],
			jsloadfu:function jsloadfu(){
					js.nowloading++;
					if(js.nowloading>=js.js.length){//js加载结束
						apiload("1");
						return true;
					}
					if(!js.js[js.nowloading][0]){
						jsloadfu();//是否加载
						return true;
					}
					var js_name=document.createElement('script');
					js_name.setAttribute('src',js.js[js.nowloading][1]);//js加载
					js._doc.appendChild(js_name);
					js_name.onload=js_name.onreadystatechange=function(){
						if(!this.readyState||this.readyState=='loaded'||this.readyState=='complete'){
							js.nowloaded++;
							if(js.nowloaded>=js.js.length){
								apiload("1");
							}else{
								jsloadfu();
							}
						}
						this.onload=this.onreadystatechange=null;
					}
				}
		};
		if(t!="flv")js.js[4][0]=0;
		if(t!="m3u8")js.js[5][0]=0;
		js.jsloadfu();

		//api引入
		function apiload(apiload_id){
			var p=localStorage.getItem("api");//取出api
			if(apiload_id=="1"){//第一次进入
				localStorage.setItem("api","null");//清除上次api
				fu_(apiload,"2");//设置第2次进入
				return true;
			}
			if(p=="null"){//如无法找到api 重新缓存
				fu_(apiload,apiload_id);
			}else{
				var o=JSON.parse(p);//取出
				if(apiload_id=="2"){//保证api调用 保证主程序可以进行
					loading_video(0,0);//加载界面
					screen_way();//手机判断
					day(o.day);//设置自定义
					flvPlayerfu();//播放器加载
					volum('apiload',611);//默认音量设置
					return true;
				}else{
					return o[apiload_id];
				}
			}
			function fu_(val,id){
				var api=new XMLHttpRequest();
				api.open("GET","json/api.json");
				api.send(null);
				api.onreadystatechange=function(){
					if(api.readyState==4&&api.status==200){
						localStorage.setItem("api",api.responseText);
						if(val)val(id);
					}
				};
			}
		}
//视频事件
	//等待界面
	var loading_video_val=0;
	function loading_video(val,count){
		if(loading_video_val==1)return false;
		var a,
			o=apiload("loading_video");
		if(val>5){
			if(count<1)a=o.a;
			else if(count<2)a=o.b;
			else if(count<3){
				a=o.c;
			}else{
				a=o.d;
			}
			loading_info.innerHTML=a;
			val=0;
			count++;
		}
		loading_info.innerHTML+=".";
		if(loading_info.style.display!="none"){
			setTimeout(function(){
				val++;
				loading_video(val,count);
			},1000);
		}
	}
	//视频可以播放时触发
	videoElement.oncanplay=function(){
		if(loading_video_val==1)return false;
		loading.style.display="block";
		loading_info.style.display="none";
		size_default(0);
		fixwin();
		if(!rectime.fu('info'))autoplay(1);
		else rectime.fu('oncanplay');
	};
	//自动播放 循环
	var autoplay_val=0,
		autoplay_firstin=0,
		autoplay_again=0,
		autoplay_mun=0;
	function autoplay(val) {//val 0：设置 1：清除
		if(screen_way_val)return false;//安卓端无法实现自动播放 只能通过手动触发事件
		if(val==1&&videoElement.currentTime<3){
			if(autoplay_firstin==0){//第一次进入此函数
				autoplay_firstin=1;
				a1();
			}
			if(autoplay_mun!=0&&autoplay_again==0)a3();//非初次播放且循环播放标志为否
			if(autoplay_again==1)a1();//开启循环播放
		}else{
			if(autoplay_mun!=0)autoplay_again=1;//当播放多次时 触发循环
			a2();
		}
		function a1(){
			if(autoplay_mun>0&&videoElement.paused&&paus.value=='播放')return false;
			div2_1_1_1.innerHTML='即将自动播放';
			if(autoplay_val)autoplay_val=clearInterval(autoplay_val);
			var autoplay_val=setTimeout(function(){
				if(videoElement.paused)pause();//避免a2()触发时仍在切换
				if(div2_1_1_1.innerHTML=='即将自动播放')div2_1_1_1.innerHTML='菜单';
				autohide.fu('autoplay',2,1);
			},1000);
		}
		function a2(){
			if(autoplay_val)autoplay_val=clearInterval(autoplay_val);
			div2_1_1_1.innerHTML='菜单';
		}
		function a3(){
			paus.value='循环？';
		}
		/*
		function auto_debug(){
			var a;
			if(val==0){a='正在播放时';}else{a='准备播放时';}
			console.log("debug:autoplay()---------------");
			console.log("触发时间:"+a+'触发。');
			console.log("当前视频时间:"+videoElement.currentTime);
			if(autoplay_firstin==0){a='是';}else{a='不是';}
			console.log("这"+a+'第一次进入');
			if(autoplay_val==0||!autoplay_val){a='关闭';}else{a='开启';}
			console.log("计时器处于"+a+'状态。');
			console.log("视频播放了"+autoplay_mun+'次');
			if(autoplay_again==0){a='没开始';}else{a='开启';}
			console.log("目前"+a+'循环');
		}auto_debug();
		*/
	}
	//视频播放时触发
	videoElement.onplay=function(){
		videolist.fu("videoElement.onplay");
		if(night()){
			videoElement.style.opacity=0.8;
			if(t!='mp3'&&t!='acc'&&t!='wav')videoplace.style.backgroundColor='black';
		}else{
			videoElement.style.opacity=1;
		}
		size_default(1);
		autoplay(0);
		rectime.fu('onplay');
	};
	//视频卡顿触发
	var cannot_play;
		cannot_play_val=0;//0:可以播放
	videoElement.onwaiting=function(){
		div2.style.display='block';
		if(cannot_play)cannot_play=clearInterval(cannot_play);//太久没加载出来 重新加载
		cannot_play=setInterval('video_cannot_play()',5000);
		div2_1_1_1.innerHTML='正在缓冲';
	};
	function video_cannot_play(){
		if(videoElement.readyState>2){
			return true;
		}
		if(videoElement.readyState==2){//未能接受到回复
			div2_1_1_1.innerHTML='无法缓冲';
			return true;
		}
		if(div2_1_1_1.innerHTML=='正在缓冲'&&!cannot_play_val){//重载
			/*
			var cu=localStorage.getItem(cu);
			if(cu=="haved"){//曾出现刷新页面 MediaError
				localStorage.setItem(cu,"null");
			}else{
			var ct=videoElement.currentTime;*/
			reloadfu();
			//console.log(ct);
			//seek(ct);
			pause();
			//}
			cannot_play_val=1;//1:勿重复进入
		}
		cannot_play=clearInterval(cannot_play);
	}
	//视频缓冲结束触发
	videoElement.onplaying=function(){
		div2_1_1_1.innerHTML='菜单';
	};
	//视频结束触发
	videoElement.addEventListener("ended",end);
	function end()
	{
		seek(0,'end');
		if(autoplay_again==1){paus.value='即将播放';}
		else{paus.value='播放';}
		videoplace.style.backgroundColor='transparent';
		videoElement.style.opacity=0.1;
		autoplay_mun++;
		videolist.fu('end');
	};
	//视频出错触发
	videoElement.onerror=function(){
		state(0);
	};
	//视频播放器事件
	function flvPlayerfu(){
		if(t=="m3u8"){
			if(Hls.isSupported()!=undefined) {
				var hls = new Hls();
				hls.loadSource(video_src());
				hls.attachMedia(videoElement);
			}
		}
		else if(t=="flv"){
				if (flvjs.isSupported()!=undefined)
				{
						flvPlayer = flvjs.createPlayer({
							type:t,
							url:'../'+u+'.'+t,
						},{
							lazyLoad:false//远程flv出现错误	
						});
					flvPlayer.attachMediaElement(videoElement);
					flvPlayer.load();
					flvPlayer.on("error",function (ErrorTypes){
						state(ErrorTypes);
					});
				}
				else{
					loading_video_val=1;
					loading_info.innerHTML='浏览器不支持 安卓可换chrome!';
				}
		}
		else{
			mediaload();
			}
		paus.value='播放';
		win(0,0,0);
		review();
		if(n!="null"){
			var a=n;
		}else{
			if(r!=0){
				var a=u;
			}else{
				var a=null;
			}
		}
		if(a!=null){
			alertfu({//播放提示
				text:"正在播放："+a,
				position: 'top-end',
				backdrop:'rgba(0,0,0,0.1)',
				showConfirmButton: false,
				timer: 3300
			},'flvPlayerfu');
		}
		//console.log(videoElement.volume);
	}
	//mediaload
	function mediaload(){
		var fe=localStorage.getItem("fetch");
		if(fe)localStorage.setItem("fetch",'null');
		if(r=='0'||!sign||fe=='error'){
			videoElement.src=video_src();//避免 no Access-Control-Allow-Origin
			videoElement.load();
		}else{
			var mimeCodec = 'video/mp4; codecs=avc1.64001e,mp4a.40.5',
				n=new Array(),//缓存
				sourceBuffer,
				mediaSource = new MediaSource,
				video_load={
			//video_load begin
			//	open begin
				check:function(){
						if (MediaSource.isTypeSupported(mimeCodec)){
							videoElement.src = URL.createObjectURL(mediaSource);
							mediaSource.addEventListener('sourceopen',this.open);
						}else{
							console.error('Unsupported MIME type or codec: ', mimeCodec);
						}
					},
				open:function (){
						console.log("mediaSource open.");
						var mediaSource = this;
						sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
						sourceBuffer.mode='sequence';
						/*
						sourceBuffer.addEventListener('updateend',()=>{
							console.log('mediaSource.activeSourceBuffers.length')
							if(mediaSource.activeSourceBuffers.length==0&&sign){
								sign=0;
								localStorage.setItem("fetch",'error');
								console.log("video codecs error");
								window.location.reload();
								return false;
							}
						});
						*/
						video_load.fetchAB(video_src(),
							function (buf){
								if(buf==0){//结束
									var ii;
									ii=setInterval(function(){//将缓存在n的数据推出
										if(!sourceBuffer.updating&&mediaSource.readyState=='open'){
												if (n.length!=0){
													sourceBuffer.appendBuffer(n.shift());
												}else{
													console.log("mediaSource close.");
													mediaSource.endOfStream();
													ii=clearInterval(ii);
												}
											}
									},1);
								}else{//正在接受
									n.push(buf);//暂存
									if(n.length>0&&!sourceBuffer.updating){//暂存有数据且不在推时推
										sourceBuffer.appendBuffer(n.shift());
									}
								}
							}
						);
				},
			//	open end
			//	fetch begin
				fetchAB:function (url_,cb_){
					var f={
						error_:function (val){
							if(val<200||val>=300){
								sign=0;
								localStorage.setItem("fetch",'error');
								console.log("link error");
								window.location.reload();
								return false;
							};
							if(mediaSource.activeSourceBuffers.length==0&&sign){
								sign=0;
								localStorage.setItem("fetch",'error');
								console.log("video codecs error");
								window.location.reload();
								return false;
							};

						},
					//
						load_:function(){
							if(typeof(fetch)=='undefined'){
								sign=0;
								localStorage.setItem("fetch",'error');
								console.log("can't use fetch");
								window.location.reload();
								return false;
							}
							fetch(url_)
								.then(
									(res)=>{
										this.error_(res.status);
										this.push_(res.body.getReader());
									}
								)
								.catch(
									(error)=>{
										this.load_();
									}
								);
						},
					//
						push_:function(reader){
							function pump(){
								reader.read().then(
									function(re){
										if (re.done){
											console.log("fetch end.");
											cb_(0);
											return true;
										}else{
											if(sign){
												cb_(re.value);
											}else{
												if(!sourceBuffer.updating){
													if(mediaSource.readyState=='open')mediaSource.endOfStream();
													return true;
												}
											}
											pump();
										}
									}
								);
							}pump();
						},
					};
					f.load_();
				}
			//	fetchAB end
				};
				video_load.check();
			//	video_load end
			//video_load end
			}
	}
	//视频错误状态事件
		function state(ErrorTypes_val){
			if(loading_video_val==1||localStorage.getItem("fetch")=='error')return false;
			console.log(localStorage.getItem("fetch"));
			var val;
			loading_video_val=1;
			//alert(ErrorTypes_val);
			//alert(val+"/"+videoElement.error);
			if(!ErrorTypes_val){
				switch(videoElement.error.code)
				{
					case 1:
					val='取回过程被用户中止';
					break;
					case 2:
					val='当下载时发生错误';
					break;
					case 3:
					val='当解码时发生错误';
					break;
					case 4:
					if(loading_info.style.display=='none'){
						val='不支持编码';
					}else{
						val='未找到资源';
					}
					break;
					default:
					break;
				}/*
				if(videoElement.error.code!=2){
					loading.style.display="none";
					loading_info.style.display="block";
					loading_info.innerHTML=val;
				}*/
			}else{
				if(ErrorTypes_val=="MediaError"){
					localStorage.setItem(u,videoElement.currentTime);//保存进度
					val='媒体错误';
				}
				else{
					if(ErrorTypes_val=='NetworkError'){
						val='网络错误';
					}else{
						val='其他错误';
					}
				}
			}
			loading.style.display="none";
			loading_info.style.display="block";
			loading_info.innerHTML=val;
			alert(val);
			console.log('video_error:'+val);
			if(val=='媒体错误')window.location.reload();//由flv.js引起的媒体错误暂时没法通过简单重载恢复
		}
		//视频区间播放
		function op_edfu(){
			var length =mouseX-loading.offsetLeft;/*offsetLeft为第2级*/
			if(length<0)length=0;
			var percent = length / progressWrap.offsetWidth;
			var a=percent * videoElement.duration;
			if(!op){
				alertfu({
					text:"开始于："+timebar(a),
					type:"info",				
					position: 'top-end',
					showConfirmButton: false,
					timer: 1000
				},'op_edfu');
				op=a;
			}else{
				if(!ed){
					ed=a;
					alertfu({
						text:"区间播放："+timebar(op)+"-"+timebar(ed),
						type:"info",
						position: 'top-end',
						showConfirmButton: false,
						timer: 2000
					},'op_edfu');
				}
			}
		}
		//回复播放时间
		var rectime={
			val:0,
			fu:function(function_){
				if(!function_||function_==null||function_==undefined||function_=='null'){
					console.log('rectime function_=?');
					return false;
				};

				var f={
					url:video_src(),
					info:function(){
						var cu=localStorage.getItem(rectime.fu('url'));//读取记录的进度
						console.log('rec:'+rectime.fu('url')+",")
						if(cu!='null'||!cu||cu==null||cu==undefined){
							if(cu>10&&cu<videoElement.duration-10){return true;}
							else {
								rectime.val=2;//无数据时 关闭恢复
								return false;
							}
						}
					},
					recover_time:function(){//回复
						if(rectime.val>0)return true;
						var cu=localStorage.getItem(rectime.fu('url'));//读取记录的进度
						if(cu!="null"){
							if(cu>10&&cu<videoElement.duration-10){
								alertfu({
									text:'恢复至'+timebar(cu)+'？ 点此取消',
									timer:5000
								},'rectime.f');
								rectime.val=1;
								setTimeout(function(){
									if(rectime.val==1){
										localStorage.setItem(rectime.fu('url'),"null");
										seek(cu,'rectime.f');
										rectime.val=2;
										pause();
									}
								},5000);
							}
						}
					},
					set_time:function(){//设置
						var cu=localStorage.getItem(rectime.fu('url'));//读取记录的进度
						if(rectime.val==2)localStorage.setItem(rectime.fu('url'),videoElement.currentTime);
					},
					norec:function(){//取消回复
						if(rectime.val==2)return true;
						alertfu({
							text:'none',
							timer:0
						},'rectime.f');
						autoplay(1);
						rectime.val=2;
					},
				};
				switch (function_){
					case 'url':
						return f.url;
						break;
					case 'info':
						return f.info();
						break;
					case 'notice_div.onclick':
					case 'seek':
					case 'onplay':
						return f.norec();
						break;
					case 'ontimeupdate':
						return f.set_time();
						break;
					case 'oncanplay':
						return f.recover_time();
						break;
					default:
						break;
				}

	
			},

		};

		//系列播放
		var videolist={
			timer:0,
			fu:function(function_){
				let x=u.lastIndexOf("\/"),
					p={
						op:u.substring(0,x),
						ed:u.substring(x+1,u.length),
					},
					f={
					a:function(){
						let host= window.location.host,
							part= window.location.pathname,
							protocol=window.location.protocol;
						if(!isNaN(p.ed)){
							if(p.ed<max){
								p.ed++;
								var val=protocol+"//"+host+part+"?u="+p.op+"/"+p.ed+'&t='+t+"&max="+max;
								window.location.href=val;
							}else{
								console.log("系列播放 到达max");
							}
						}
						return true;
					},
					b:function(){
						if(videolist.timer)videolist.timer=clearTimeout(videolist.timer);
						return true;
					},
					c:function(){
						if(max>p.ed&&autoplay_mun==1){//系列播放
							alertfu({//播放提示
									text:"5s后播放系列 按播放取消",
									position: 'top-end',
									backdrop:'rgba(0,0,0,0.1)',
									showConfirmButton: false,
									timer: 2000
								},'videolist.fu');
							videolist.timer=setTimeout(function(){
								videolist.fu('videolist');
							},5000);
						}
						return true;
					}
				};

				if(max==undefined||max=='null'||!max){
					console.log("系列播放 max=?");
					return false;
				}

				if(r=="0"||r==0){
					console.log("系列播放 外链暂不支持");
					return false;
				}

				switch(function_){
					case 'videolist':
						f.a();
						break;
					case 'videoElement.onplay':
						f.b();
						break;
					case 'end':
						f.c();
						break;
					default:
						console.log("未知的呼叫源");
						break;
				};
			}
		}
	

//尺寸
	//获取窗口长宽比
	//var loading_h,
	//	loading_w;
	function win(way,winx,winy){
		if(way==0){
			if (window.innerWidth)
			winWidth = window.innerWidth*0.95;
			else if ((document.body) && (document.body.clientWidth))
			winWidth = document.body.clientWidth*0.95;
			if (window.innerHeight)
			winHeight = window.innerHeight*0.95;
			else if ((document.body) && (document.body.clientHeight))
			winHeight = document.body.clientHeight*0.95;
		}else{
			winWidth=winx;
			winHeight=winy;
		}		
		W_H=winWidth/winHeight;
	}
	//适应窗口调整元素尺
	document.body.onresize=resizefu;
	function resizefu(){
		if(autofixwin_val==1){
			win(0,0,0);
			fixwin();
		}
	}
	//视频尺寸设定
	function size_default(val){
		if(videoElement.videoWidth!=0&&videoElement.videoWidth){
			H=videoElement.videoHeight;//视频高度
			W=videoElement.videoWidth;//视频宽度
		}else{
			if(H!=720){
				H=720;//视频
				W=1280;
				if(val==0){
					console.log('size_default:videoheight&width不存在.');
					console.log("size_default:视频使用默认尺寸"+H+"*"+W+".");
				}
			}
		}
	}
	//视频自动填满窗口
	function fixwin() {
		var w_h=W/H,
			rotate_0or2=rotatevalue==0||rotatevalue==2,
			val=0;
			//console.log(W_H);
			if(W_H>1)val+=1000;
			if(w_h>1)val+=100;//浏览器窗口宽大于高
			if(rotate_0or2)val+=10;
			if(rotate_0or2&&W_H>w_h)val+=1;
			if(!rotate_0or2&&w_h*W_H>1)val+=1;
		/*
		if(W_H>1)
		{
			if(w_h>1)//浏览器窗口宽大于高
			{
				if(rotate_0or2)
				{
					if(W_H>w_h){
						hh();//1111
					}else{
						ww();//1110
					}
				}else{//110x
					wh();
				}
			}else{
				if(rotate_0or2)
				{
					hh();//101x
				}else{
					if(w_h*W_H>1){
						wh();//1001
					}else{
						hw();//1000
					}
				}
			}
		}else{
			if(w_h<1)
			{
				if(rotate_0or2)
				{
					if(W_H>w_h){
						hh();//0011
					}else{
						ww();//0010
					}
				}else{
					hw();//000x
				}
			}else{
				if(rotate_0or2)
				{
					ww();//011x
				}else{
					if(w_h*W_H>1){
						wh();//0101
					}else{
						hw();//0100
					}
				}
			}
		}*/
		//console.log(val+"/"+winHeight);
		switch(val){
			case 1111:
			case 1011:
			case 1010:
			case 11:
				hh();break;
			case 1110:
			case 110:
			case 111:
			case 10:
				ww();break;
			case 1101:
			case 1100:
			case 101:
			case 1001:
				wh();break;
			default:
				hw();break;
			/*
			default包括
			case 1000:
			case 100:
			case 1:
			case 0:
			*/
		}
		function hh(){w=W*winHeight/H;h=winHeight;}
		function ww(){h=H*winWidth/W;w=winWidth;}
		function wh(){h=H*winHeight/W;w=winHeight;}
		function hw(){w=W*winWidth/H;h=winWidth;}
		if(w/14>45&&w/14<70){
			var input_w=w/14;
			div1.style.top='';
		}else{
			if(w/14<45){
				if(!input_w){var input_w=50;}else{input_w=50;}
				div1.style.top=h+'px';
			}else if(w/14>70){
				if(!input_w){var input_w=70;}else{input_w=70;}
				div1.style.top='';
			}
		}
		for(var val=0;val<input.length;val++){
			input[val].style.width=input_w+"px";//动态调整按钮宽度
			if(input[val].value=='下载')break;
		}
		videoElement.style.height=h+"px";
		videoElement.style.width=w+"px";
		if(rotate_0or2)
		{
			videoElement.style.top="0px";
			videoElement.style.left="0px";//调整视频位置
			//console.log(winWidth+"/"+videoElement.offsetWidth+"/"+window.outerWidth);
			//videoElement.style.transform+='translate(0px,0px)';
			div2.style.width=(w+5)+"px";//菜单宽度适应
			div1.style.height=h/2+"px";//菜单触发高度
			div1.style.width=w+"px";
			videoplace.style.width=w+"px";
			videoplace.style.height=h+"px";
			notice_div.style.top=h-notice_div.clientHeight-2+"px";
		}else{
			videoElement.style.top=(w-h)/2+"px";
			videoElement.style.left=(h-w)/2+"px";
			div2.style.width=h+5+"px";
			div1.style.height=w/2+"px";
			div1.style.width=h+"px";
			videoplace.style.width=h+"px";
			videoplace.style.height=w+"px";
			notice_div.style.top=w-notice_div.clientHeight-2+"px";
		}
	}

//按钮事件
	//暂停键设置
	paus.onclick=pause;
	function pause(){
		if(videoElement.paused){
			videoElement.play();
			paus.value=('暂停');
		}else{
			videoElement.pause();
			paus.value=('播放');
		}
	}
	//重加载
	reload.onclick=reloadfu;
	function reloadfu(){
		div2_1_1_1.innerHTML='菜单';
		videoElement.src='';
		speedval=0;
		flvPlayerfu();
	}
	//旋转
	rotate.onclick=routate_onclick;
	function routate_onclick(){
		rotatevalue+=1;
		var val="rotate("+90*rotatevalue+"deg)";
		if(rotatevalue==4)rotatevalue=0;
		videoElement.style.webkitTransform=val;
		videoElement.style.msTransform=val;
		videoElement.style.MozTransform=val;
		videoElement.style.OTransform=val;
		videoElement.style.transform=val;
		fixwin();
		onprogressfu();
	};
	//去源址
	soure.onclick=function (){
		if(r==null){
			console.log("没有源地址");
			return false;
		}
		if (soure.value=="去B站"){
			window.location.href='http://www.bilibili.com/video/av'+r;
		}else{
			if(r!=0){
				window.location.href=r;
			}else{
				window.location.href=u+'.'+t;
			}
		}
	};
	//是否开启bilibili链接
	function link(bililink){
		if(r!=0){
			if (!isNaN(r)&&bililink==1)soure.value="去B站";
		}
	}link(1);
	//键盘事件
	document.onkeydown=function(e){
		//var e = event || window.event || arguments.callee.caller.arguments[0];
		if(!e)var e=window.event;
		let prevent=0;
		switch(e && e.keyCode){
			case 37:
				time(0,-currentTime);
				break;
			case 38:
				volum('document.onkeydown',volume);
				break;
			case 39:
				time(1,currentTime);
				break;
			case 40:
				volum('document.onkeydown',-volume);
				break;
			case 70:
				fullscreenfu();
				break;
			case 82:
				routate_onclick();
				break;
			case 86:
				speed_onclick();
				break;
			default:
				prevent=1;
				break;
		}
		if(prevent==0)e.preventDefault();
		function time(val,change){
			autohide.fu('time',2,1);
			var a=videoElement.currentTime+change;
			if(a>videoElement.duration||a<0){//防止超出范围
				if(val==0){a=0;}else{a=videoElement.duration;}
				seek(a,'time');
			}else{
				seek(videoElement.currentTime+change,'time');
			}
		}
	};
	document.onkeyup=function(e){
		if(!e)var e=window.event;
		if(e && e.keyCode==32)pause();
	};
	//音量 速度设置
	var speedval=0;//0:音量 1：速度
	speed.onclick=speed_onclick;
	function speed_onclick(){
		//console.log(videoElement.volume);
		if(speedval==0){
			alertfu({
				text:'速度',
				timer:1000
			},speed_onclick);
			volumerange.max="100";
			speed.value="音量v";
			volumerange_val.innerHTML='速度(点此原速)';
			volumerange.value=videoElement.playbackRate*50;
			showinfo.innerHTML=Math.floor(videoElement.playbackRate*100)+"%";
			speedval=1;
		}else{
			alertfu({
				text:'音量',
				timer:1000
			},speed_onclick);
			volumerange.max="100";
			speed.value="速度v";
			volumerange_val.innerHTML='音量';
			volumerange.value=videoElement.volume*100;
			//console.log(volumerange.value);
			//console.log(videoElement.volume);
			showinfo.innerHTML=Math.floor(videoElement.volume*100)+"%";
			speedval=0;
		}
	};
	volumerange.onchange=function (){
		volum('volumerange.onchange',volumerange.value+1);
		//console.log("aaaa"+volumerange.value+1);
	};
	volumerange_val.onclick=function(){
		if(speedval==0)return false;
		volum('volumerange_val.onclick',501);
	};
	function volum(function_,a){
		if(!speedval){//音量
			if(a>=1){
				a-=1;videoElement.volume=(a/1000);//拖动条
			}else{
				videoElement.volume+=((videoElement.volume+a)<=1&&(videoElement.volume+a)>=0)?a:0;//键盘
				if((videoElement.volume+a)>1)videoElement.volume=1;
				if((videoElement.volume+a)<0)videoElement.volume=0;
			}
			showinfo.innerHTML=Math.floor(videoElement.volume*100)+"%";
			volumerange.value=videoElement.volume*100;
		}else{//速度
			//console.log(a);
			if(a>=1){
				a-=1;
				videoElement.playbackRate=a/500;
			}else{
				videoElement.playbackRate+=((videoElement.playbackRate+a)>=0&&(videoElement.playbackRate+a)<=2)?a:0;
				if(videoElement.playbackRate+a>2)videoElement.playbackRate=2;
				if(videoElement.playbackRate+a<0)videoElement.playbackRate=0;				
			}
			showinfo.innerHTML=Math.floor(videoElement.playbackRate*100)+"%";
			volumerange.value=videoElement.playbackRate*50;
		}
		
		if(function_!='apiload'){
			let a;
			if(speedval==0)a='当前音量:'+Math.floor(videoElement.volume*100)+"%";
			else a='当前速度:'+Math.floor(videoElement.playbackRate*100)+"%";
			alertfu({
				text:a,
				timer:1000
			},'volum');
		}

	}
	//全屏
	videoElement.ondblclick=function(){
		if(!screen_way_val){
			fullscreenfu();
		}
	};
	fullscreen.onclick=function (){
		fullscreenfu();
	};
	document.onwebkitfullscreenchange=function(e){fullscreen_info();};
	document.onmozfullscreenchange=function(e){fullscreen_info();};
	document.onfullscreenchange=function(e){fullscreen_info();};
	function fullscreen_info(){
		var fullscreen_val;
		if(window.fullScreen!=undefined)fullscreen_val=window.fullScreen;
		if(document.webkitIsFullScreen!=undefined)fullscreen_val=document.webkitIsFullScreen;
		if(fullscreen_val){
			fullscreen.value='退出';
		}else{
			fullscreen.value='全屏f';
		}
	}
	function fullscreenfu(){
		var fullscreen_val;
		if(window.fullScreen!=undefined)fullscreen_val=window.fullScreen;
		if(document.webkitIsFullScreen!=undefined)fullscreen_val=document.webkitIsFullScreen;
		//console.log(document.fullscreenEnabled+"/"+window.fullScreen+"/"+document.webkitIsFullScreen+"/"+document.msFullscreenEnabled);
		if(!fullscreen_val){
			if (videoElement.requestFullscreen){
				videoElement.requestFullscreen();
			} else if (videoElement.mozRequestFullScreen) {
				videoElement.mozRequestFullScreen();
			} else if (videoElement.webkitRequestFullScreen) {
				videoElement.webkitRequestFullScreen();
			}
		}else{
			if(document.exitFullscreen){
				document.exitFullscreen();
			}else if(document.mozCancelFullScreen){
				document.mozCancelFullScreen();
			}else if(document.webkitExitFullscreen){
				document.webkitExitFullscreen();
			}
		}
		//loading.style.margin='0 auto';
	}
	//下载
	function downloadfu(){
		var val,
			r=GetQueryString("r"),
			t=GetQueryString("t"),
			u=GetQueryString("u");
		if(r!=0){
			val='../'+u+'.'+t;
		}else{
			val=u+'.'+t;
		}
		return val;
	}
	//区间播放
	oped.onclick=function(){
		if(oped.value=='区间'){
			alertfu({
				title:'区间设置',
				text:"点击进度条设置出入点",
				position: 'top-end',
				showConfirmButton: false,
				timer: 2000
			},'oped.onclick');
			oped.value='清除';
			set_oped=1;
		}
		else{
			op=0;ed=0;
			oped.value='区间';
			set_oped=0;
		}
	}

//进度条
	//进度条设置
		//刷新进度条
		function review(){
			onprogressfu();
			getProgress();
		}
		//加载条事件
		videoElement.onprogress=onprogressfu;
		function onprogressfu(){
			var timeRages=videoElement.buffered;
			if(timeRages.length!=0)var timeBuffered = timeRages.end(timeRages.length-1);
			if(!timeBuffered)return true;
			seek_info();
			if(autoplay_mun==0&&timeBuffered<videoElement.duration){
				var bufferPercent = timeBuffered/videoElement.duration;
				loadProgress.style.width=bufferPercent*progressWrap.offsetWidth+"px";
			}else{
				loadProgress.style.width=progressWrap.offsetWidth+"px";
				setTimeout(function(){//加载完成后去掉样式
					var css_classf=loadProgress.getAttribute("class");
					var css_class=css_classf.replace("progress-bar progress-bar-success progress-bar-striped active","");
					loadProgress.setAttribute("class",css_class);	
				},1000);
			}
		}
		//进度条事件
		videoElement.ontimeupdate=function(){
			rectime.fu('ontimeupdate');//回复播放时间
			if(div2.style.display!='none')getProgress();
			if(!videoElement.paused)div2_1_1_1.innerHTML='菜单';//edge不触发onplay onplaying
			if(set_oped&&ed){//自定义区间播放
				var a=videoElement.currentTime>ed,
					b=videoElement.currentTime<op;
				if(op<ed){
					if(a||b){
						seek(op+1,'ontimeupdate');
					}
				}else{
					if(a&&b){
						seek(op+1,'ontimeupdate');
					}
				}
			}
		};
		function getProgress(){
			playProgress.style.width=videoElement.currentTime/videoElement.duration*progressWrap.offsetWidth+"px";
			showProgress.innerHTML=timebar(videoElement.currentTime);
			if(videoElement.duration!=0&&videoElement.duration){
				//console.log(videoElement.duration);
				if(lookProgress.innerHTML=='/0s'||!lookProgress.innerHTML||r=='live'){
					lookProgress.innerHTML='/'+timebar(videoElement.duration);
				}
			}else{
				lookProgress.innerHTML='/0s';
			}
			if(mouse_inpro)lookProgress_info();
		}
	//时间计算事件
	function timebar(time_val){
		var timebar_val='',
			h=Math.floor(time_val/3600),
			m=Math.floor(time_val/60%60),
			s=Math.floor(time_val%60);
		if(h)timebar_val+=h+'h';
		if(m)timebar_val+=m+'min';
		timebar_val+=s+'s';
		return timebar_val;
	}
	//进度条引索显示
	function lookProgress_info(){
		var length =mouseX-loading.offsetLeft;/*offsetLeft为第2级*/
		if(length<0)length=0;
		var percent = length / progressWrap.offsetWidth;
		var a=timebar(percent * videoElement.duration);
		if(length>=showProgress.offsetWidth){
			if(percent<0.5){
				lookProgress.style.left=length-showProgress.offsetWidth+'px';
				a="|"+a;
			}else{
				lookProgress.style.left=length-lookProgress.offsetWidth-showProgress.offsetWidth+'px';
				a=a+"|";
			}
			lookProgress.innerHTML=a;
		}else{
			lookProgress.innerHTML='/'+a;
		}
	}
	progressWrap.onmouseout=function (e)
	{
		function val(){
			//div2.style.opacity=0.7;
			lookProgress.innerHTML='/'+timebar(videoElement.duration);
			lookProgress.style.left="0px";
			if(mouse_inpro)mouse_inpro=0;
		}
		room(e,val,this);
	};
	//拖动进度条设置
	var mousedown=0;//默认鼠标为抬起
	document.onselectstart=new Function("event.returnValue=false;");
	progressWrap.onmousedown=function(e){
		if(e.buttons==2)return false;//禁右键
		if(set_oped&&!ed){
			op_edfu();
			return true;
		}
		if(!e)var e=window.event;
		mousedown=1;
		div2.style.opacity=0.3;
		seek('null','onmousedown');
		lookProgress_info();
	};
	window.onmouseup=function(){
		mousedown=0;
		div2.style.opacity=0.7;
	};
	progressWrap.onmousemove=function (e){
		if(!e)var e=window.event;
		mouseX=e.pageX;//更新鼠标位置
		if(!mouse_inpro)mouse_inpro=1;//如果位于进度条上则设为1 在getpro..中更新
		lookProgress_info();
		if(mousedown==1){
			seek('null','onmousemove');
		}
	};
	var seek_val=0,
		seek_info=function(){
			if(!seek_val)return true;
			var timeRages=videoElement.buffered;
			if(timeRages.length==0)return false;//播放flv频繁拖动时发生缓存长度为0 为避免error 拒接此次拖动
			var timeBuffered = timeRages.end(timeRages.length-1);	
			if(seek_val<timeBuffered){
				alertfu({
					text:'已跳转',
					timer:1000
				},'seek');
				seek(seek_val,'seek_info');
				seek_val=0;
			}
			return true;
		},
		seek=function(val,function_){
			var timeRages=videoElement.buffered;
			if(timeRages.length==0)return false;//播放flv频繁拖动时发生缓存长度为0 为避免error 拒接此次拖动
			var timeBuffered = timeRages.end(timeRages.length-1);
			var length = mouseX - loading.offsetLeft;/*offsetLeft为第2级*/
			var percent = length/progressWrap.offsetWidth;
			if(val!=undefined&&val!='null'&&val!=null)percent= val/videoElement.duration;
			if(percent*videoElement.duration<=timeBuffered){
				var a=percent*videoElement.duration;
			}else{
				if(t!='mp4'){
					alertfu({
						text:'缓冲中 届时将自动跳转(点已缓冲部分取消)',
						timer:5000
					},'seek');
					seek_val=percent*videoElement.duration;
					return true;
				}
				a=percent*videoElement.duration;
			}
			if(a<0)a=0;
			if(a>videoElement.duration)a=videoElement.duration;
			playProgress.style.width =percent*(progressWrap.offsetWidth)+"px";
			if(t=="flv")flvPlayer.currentTime=a;
			else videoElement.currentTime =a;
			rectime.fu('seek');//play
			if(function_!='seek_info'&&seek_val!=0)
			{
				seek_val=0;
				alertfu({
					text:'已取消跳转',
					timer:2000
				},'seek');
			}
			showProgress.innerHTML=timebar(videoElement.currentTime);//此处先行刷新当前时间 避免后续错位
	};

//背景
	var day_inuse=1,
		day=function (o){
				function background(type,use){
					if(autofixwin_val==0)return false;
					if(type==1){
						document.body.backgroundColor=use;
					}else{
						document.body.style.backgroundImage='url('+use+')';
						document.body.style.backgroundSize='cover';
						document.body.style.backgroundRepeat='repeat-y';
						document.body.style.backgroundAttachment='fixed';
					}
				}
		
				if(night()){
					var a=new Array();
					a=[loading_info,lookProgress,showProgress,div2_1_1_1];
					for(var n=0;n<a.length;n++){
						a[n].style.color='white';
					}
					for(var val=0;val<input.length-1;val++){
						input[val].style.color="white";
						if(input[val].value=='下载')break;
					}
					div2.style.backgroundColor=o.n_div2color;
					playProgress.style.backgroundColor='white';
					day_time.innerHTML=o.n_say;
					if(day_inuse){
						if(screen_way_val){
							background(1,o.phone_n);
						}else{
							background(2,o.n_pic);
						}
					}
				}else{
					day_time.innerHTML=o.d_say;
					if(day_inuse){
						if(screen_way_val){
							background(1,o.phone_d);
						}else{
							background(2,o.d_pic);
						}
					}
				}
				if(screen_way_val)div2.style.top=0+'px';
			};

//菜单
	//自动隐藏
	var autohide={
		set_timer:0,
		fu:function(function_,hide_time,vall){
			//if(function_=="videoElement.onclick"&&mousedown==0)return true;
			var val_,
				val;
			if(vall){
				val="inline";
				val_="none";
			}else{
				val="none";
				val_="inline";
			}
			div2.style.display=val;
			if(function_=='volum'){
				div2_1_1_1.style.display=val_;
				div2_1.style.display=val;
			}
			if(autohide.set_timer)clearTimeout(autohide.set_timer);
			autohide.set_timer=setTimeout(function(){
				if(div1_mouseover)return true;//若鼠标悬浮在菜单上取消
				if(div2.style.display!=val_){
					div2.style.display=val_;
					if(function_=='volum'){
						div2_1_1_1.style.display=val;
						div2_1.style.display=val_;
					}
				}
				autohide.set_timer=null;
			},hide_time*1000);
		},
	}
	//点击显示
	videoElement.onclick=function (){
		if(div2.style.display=="none"){
			autohide.fu('videoElement.onclick',8,1);
			review();
		}else{
			if(!screen_way_val){
				div2.style.display="none";
			}else{
				if(div2_1.style.display=='none'||!div2_1.style.display){
					div2_1.style.display='inline';
					div2_1_1_1.style.display='none';
				}else{
					div2.style.display='none';
					div2_1.style.display='none';
					div2_1_1_1.style.display='inline';
				}	
			}
		}
	};
	//主控制
	var div1_mouseover=0;
	div1.onmouseover=function(e)
	{
		function val(){
			div1_mouseover=1;
			div2.style.display="inline";
			review();//刷新进度条
		}
		room(e,val,this);
	};
	div1.onmouseout=function (e)
	{
		function val(){
			div1_mouseover=0;
			autohide.fu('div1.onmouseout',1,1);
		}
		room(e,val,this);
	};
	//菜单
	div2_1_1.onmouseover=function (e){
		function val(){div2_1.style.display="inline";div2_1_1_1.style.display="none";}
		room(e,val,this);
	};
	div2_1_1.onmouseout=function (e){
		room(e,menunone,this);
	};
	function menunone(){
		div2_1_1_1.style.display='inline';
		div2_1.style.display='none';
	}menunone();

//工具
	//鼠标范围
	/*确定鼠标在某一元素上 lo:this*/
	function room(e,val,lo){
		if(!e)var e = window.event;
		var reltg = e.relatedTarget ? e.relatedTarget : e.fromElement;
		while (reltg && reltg != lo) reltg = reltg.parentNode;
		if (reltg !=lo) {
			val();
		}
	}
	//时间
	function night(){
		var myDate = new Date(),
			a=false;
		if(myDate.getHours()<6||myDate.getHours()>17)a=true;
		return a;
	}
	//显示器方向
	function screen_way() {
		var screen_way_val=false,
			wo=new Object(window.orientation);
		if (wo == 180 || wo == 0|| wo == 90 || wo == -90)screen_way_val=true;
		//alert(wo);
		if (wo==180||wo==0){
			if(!videoElement.paused)pause();
			loading.style.display='none';//隐藏播放器
			loading_video_val=1;//停止loadvideo 和 canplay 
			loading_info.innerHTML='请横屏观看';//显示提示
			localStorage.setItem("currentTime",videoElement.currentTime);
		}
		if(screen_way_val)div2_1_1_1.innerHTML='再次点击打开菜单';
		return screen_way_val;
	}
	window.onorientationchange=function(){
		screen_way();
		if(loading_info.innerHTML!='请横屏观看')return true;
			window.location.reload();//旋转之后重载
	}
	//视频地址
	function video_src(){
		var val='';
		if(r!=0&&r!='live'){
			val='../'+u+'.'+t;
		}else{
			val=u+'.'+t;
		}
		return val;
	}
	//获取参数
	function GetQueryString(name){
		var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
		var r = window.location.search.substr(1).match(reg);
		if(r!=null)return  decodeURI(r[2]); return null;
	}
	//通知样式
	/*
	 *sweetalert2
	 *https://github.com/sweetalert2/sweetalert2
	 */
	notice_div.onclick=function(){
		rectime.fu('notice_div.onclick');
	};
	function alertfu(val,function_){
		if(!val||val=='null'||val==null||val==undefined){
			console.log('alertfu val=?');
			return false;
		}
		if(!function_||function_=='null'||function_==null||function_==undefined){
			console.log('alertfu function_=?');
			return false;
		}
		switch (function_){
			case 'xx':
				swal(val);
				break;
			default:
				notice.fu('alertfu',val.text,val.timer/1000);
				break;
		}
	}
	//error检测
	window.addEventListener("error",function(msg,url,l){
		console.log(msg);
	});
	//提示信息
	var notice={
		time:0,
		fu:function(function_,val,time){

			if(function_==null||function_==undefined||function_=="null"){
				console.log("notice.fu function_=?");
				return false;
			}

			if(val==null||val==undefined||val=="null"){
				console.log("notice.fu val=?");
				return false;
			}
			if(time==null||time==undefined||time=="null"){
				console.log("notice.fu time=?");
				return false;
			}
			if(time==0){
				notice_div.style.display='none';
				return true;
			}
			notice_div.innerHTML=val;
			notice_div.style.display='inline';
			fixwin();
			if(time=='nohide')return true;
			if(notice.time)notice.time=clearTimeout(notice.time);
			notice.time=setTimeout(function(){
				notice_div.style.display='none';
			},time*1000);
		}
	};

/*
//timer
var timer_max=5;//设置定时器限量
for(var timer_num=0;timer_num<timer_max;timer_num++){//批量定义变量并赋值
	var timer_dir='gra'+timer_num,
		timer_dir2='grb'+timer_num;
		window[timer_dir] ='';
		window[timer_dir2] ='';
}
function timer(val,fu){
	//避免重复设置计时器部分
	for(var use0,use1,a=0;a<timer_max;a++){
		use0=eval('grb'+a);//use0取出计时器状态：grb
		use1=eval('gra'+a);//*use1取出计时器方法名：gra
		if(use1==fu){//*遍历查询是否已有同名未完结计时器
			eval('gra'+a+'="";');//*清除该序号对应方法名
			if(use0)//检查该定时器是否结束
			cle_Timer(use0,a);//*清除计时器
			break;
		}
	}
	function cle_Timer(use0,id){
		clearTimeout(use0);
		eval('grb'+id+'=0;');
		//console.log('清除计时器：序号-'+id+' 方法名-'+fu);//*控制台输出
	}
	//
	for(var use0,use1,a=0;a<timer_max;a++){
		use0=eval('grb'+a);//use0取出计时器状态：grb**
		use1=eval('gra'+a);//*use1取出计时器方法名：gra**
		if(!use0){//*遍历查找没有计时器的序号*
			set_Timer(val,a,fu);//*设置计时器*
			break;
		}
		if(a>timer_max-1){
			console.log('计时器数目达到限制');
			break;
		}
	}
	function set_Timer(val,id,fu){
		eval('gra'+id+'=fu;');//*将方法名赋予原变量gra**
		eval('grb'+id+'=setTimeout(function(){'+fu+'();grb'+id+'=0;},val);');//设置定时器，规定结束时状态置零
		//console.log('设置计时器：序号-'+id+' 方法名-'+fu);//*控制台输出*
	}
}
*/